/*
 * @(#) ShowDetail.js
 *
 * <br> Copyright:  Copyright (c) 2017
 * <br>
 * <br> @author caijinhuang
 * <br> 2017-12-01 14:46:31
 */

import React  from 'react';
import "../../../css/detail.css"
import {UserUtil} from "../../UserUtil";
import {
    FormControl,
    FormGroup,
    InputGroup,
    Table,
    Button,
    Modal,
    Label,
    OverlayTrigger,
    Popover,
    Tooltip,
    DateTime,
    Form,
    Icon,
    ProgressBar,
    Panel,
    ControlLabel,
    Textarea,
    Breadcrumb
} from '@share/shareui';
import Title from "../mainList/Title";
class ShowDetail extends React.Component {

    constructor(props){
        super(props);
        console.info("参数1：",this.props.location.search);
        let paramsMap = this.getAllParams();
        this.state = {
            data:{},//数据集
            noteContent:'',//会议备注
            id:paramsMap["id"],//会议id
            username:paramsMap["username"],
            decisionFinished:"",//决议完成情况
            resetDecition:[],//决议修改表单
            resetCopy:[],//决议修改该表单复制数值，用于重置表单

            /*列表组件*/
            decitionList:[],//决议列表
            noteList:[],//备注列表
            memberList:[],//参会成员列表
            attachmentList:[],//附件列表
        }
        this.init();

    }

    /**
     * 获取url请求参数
     */
    getAllParams(){
        console.log(this.props.location)
        let paramStr = this.props.location.search.replace("?","");
        let paramsArray = paramStr.split("&");
        let paramsMap = [];
        for(var key in paramsArray) {
            paramsMap[paramsArray[key].split("=")[0]] = paramsArray[key].split("=")[1];
        }
        return paramsMap;
    }

    /*添加会议备注*/
    addNote(){
        if(this.state.noteContent !== ""){
            let url = "sharemeeting/meeting/addNote.do";
            /*异步请求*/
            fetch(url,{
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                credentials: 'include',
                xhrFields: {
                    withCredentials: true
                },
                body:JSON.stringify({meetingId:this.state.id,content:this.state.noteContent}),
            }).then((response) => response.json()) //把response转为json
                .then((responseData) => { // 上面的转好的json
                    if(responseData.status === true){
                        this.state.noteContent = "";
                        this.close();
                        this.init();
                    }else{
                        alert(responseData.msg);
                    }
                }).catch((error)=> {})
        }else{
            alert("内容不能为空，请认真填写备注");
        }
    }

    /*请求获取会议详细信息*/
    init(){
        this.state.attachmentList=[];
        this.state.decitionList=[];
        this.state.memberList=[];
        this.state.noteList=[];
        let url = "/sharemeeting/meeting/showDetail.do";
        /*异步请求*/
        fetch(url,{
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            credentials: 'include',
            xhrFields: {
                withCredentials: true
            },
            body:JSON.stringify({meetingId:this.state.id}),
        }).then((response) => response.json()) //把response转为json
            .then((responseData) => { // 上面的转好的json
                if(responseData.status === true){
                    console.log(responseData.data);
                    responseData.data.meetingTime = new Date(responseData.data.meetingTime).toLocaleString().replace(/\//g, "-");
                    this.resetRender(responseData.data);//渲染组件
                }else{
                    alert(responseData.msg);
                }
            }).catch((error)=> {})
    }

    resetRender(data){
        this.priorityState = ["超期","紧急","高","中","低"];
        this.priorityStateColor = ["danger","warning","info","primary","success"];
        this.mineId = [];
        this.decisionId = [];
        this.state.resetDecition = [];
        for(let i=0;i<data.decisionList.length;i++){
            var decisionUser = '';
            this.state.decisionFinished = '-';
            for(let j=0;j<data.decisionList[i].decisionPerformerList.length;j++){
                var nickname = data.decisionList[i].decisionPerformerList[j].nickname;
                if(nickname === UserUtil.userInfo.nickname){
                    this.mineId.push(data.decisionList[i].decisionPerformerList[j].decisionPerformerId);
                    this.decisionId.push(data.decisionList[i].decisionPerformerList[j].noteDecisionId);
                    this.state.decisionFinished = data.decisionList[i].decisionPerformerList[j].finished;
                }
                decisionUser = decisionUser + nickname + "、";
            }
            data.decisionList[i].decisionEndTime = new Date(data.decisionList[i].decisionEndTime).toLocaleString().replace(/\//g, "-");
            let stateInfo = "default";
            this.priorityState.forEach((value,index,array)=>{
                if(value===data.decisionList[i].priority){
                    stateInfo = this.priorityStateColor[index];
                }
            })
            /**
             * 决议列表
             */
            if(this.state.decisionFinished==="-"){
                this.state.decitionList.push(
                    <tr key={data.decisionList[i].noteDecisionId} data-id={data.decisionList[i].noteDecisionId}>
                        <td><Label bsStyle={stateInfo}>{data.decisionList[i].priority}</Label></td>
                        <td>{data.decisionList[i].decisionContent}</td>
                        <td>{data.decisionList[i].decisionEndTime}</td>
                        <td>{decisionUser}</td>
                        <td>{data.decisionList[i].finished}/{data.decisionList[i].shareNumber}</td>
                        <td>
                            {this.state.decisionFinished}
                        </td>
                    </tr>);
            }else if(this.state.decisionFinished === 100){
                this.state.decitionList.push(
                    <tr key={data.decisionList[i].noteDecisionId} data-id={data.decisionList[i].noteDecisionId}>
                        <td><Label bsStyle={stateInfo}>{data.decisionList[i].priority}</Label></td>
                        <td>{data.decisionList[i].decisionContent}</td>
                        <td>{data.decisionList[i].decisionEndTime}</td>
                        <td>{decisionUser}</td>
                        <td>{data.decisionList[i].finished}/{data.decisionList[i].shareNumber}</td>
                        <td><Label bsStyle="success">完成</Label></td>
                    </tr>);
            }else{
                this.state.resetDecition.push({decisionId:this.decisionId[i],mineId:this.mineId[i],finished:""});
                this.state.decitionList.push(
                    <tr key={data.decisionList[i].noteDecisionId} data-id={data.decisionList[i].noteDecisionId} data-index={this.mineId.length-1}>
                        <td><Label bsStyle={stateInfo}>{data.decisionList[i].priority}</Label></td>
                        <td>{data.decisionList[i].decisionContent}</td>
                        <td>{data.decisionList[i].decisionEndTime}</td>
                        <td>{decisionUser}</td>
                        <td>{data.decisionList[i].finished}/{data.decisionList[i].shareNumber}</td>
                        <td className="ui-numberopt">
                            <input type="text" defaultValue={this.state.decisionFinished} onChange={(e)=>{
                                if(/^[1-9]\d*$/.test(e.target.value) && e.target.value <= 100){
                                    var iflag = e.nativeEvent.path[2].getAttribute("data-index");
                                    console.log(this.mineId.length);
                                    console.log(iflag);
                                    this.state.resetDecition[iflag] = {decisionId:this.decisionId[iflag],mineId:this.mineId[iflag],finished:e.nativeEvent.path[0].value};
                                }else{
                                    if(e.target.value !== ""){
                                        e.target.value = 0;
                                    }
                                }
                            }}/>%
                        </td>
                    </tr>
                );
            }
        }

        /**
         * 成员列表
         */
        for(let i=0;i<data.attenderList.length;i++) {
            this.state.memberList.push(
                <tr>
                    <td>{data.attenderList[i].nickname}</td>
                    <td>{data.attenderList[i].state}</td>
                </tr>
            );
        }
        /**
         * 附件列表
         */
        for(let i=0;i<data.attachmentList.length;i++){
            let self = this;
            var url = "/sharemeeting"+data.attachmentList[i].attachmentUri;
            this.state.attachmentList.push(
                <div className="file-list" >
                    <Icon className="fa fa-file"/> <a href={url} target="_blank" >{data.attachmentList[i].attachmentName}</a>
                </div>
            );
        }
        /*会议备注*/
        for(let i=0;i<data.noteList.length;i++){
            data.noteList[i].noteTime = new Date(data.noteList[i].noteTime).toLocaleString().replace(/\//g, "-");
            this.state.noteList.push(
                <tr>
                    <td>{data.noteList[i].nickname}</td>
                    <td>{data.noteList[i].noteTime}</td>
                    <td>{data.noteList[i].noteContent}</td>
                </tr>
            )
        }
        this.setState({data : data});
    }
    /*关闭弹出层*/
    close(){
        this.setState({showDecision:false});
    }
    /*更改决议进度*/
    commitProgress(e){
        /*过滤掉没有修改的内容*/
        this.state.resetCopy = this.state.resetDecition.filter((v,i)=>{
            if(v.finished !== ""){
                return v;
            }
        });
        if(this.state.resetCopy.length===0){
            alert("未做任何修改，无需提交");
        }else{
            let url = "/sharemeeting/meeting/changeProgress.do";
            /*异步请求*/
            fetch(url,{
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                credentials: 'include',
                xhrFields: {
                    withCredentials: true
                },
                body:JSON.stringify({decisions:this.state.resetCopy}),
            }).then((response) => response.json()) //把response转为json
                .then((responseData) => { // 上面的转好的json
                    if(responseData.status === true){
                        this.state.resetDecition.forEach((value,index,array)=>{
                            value.finished = "";
                        });
                        this.close();
                        this.init();
                    }else{
                        alert(responseData.msg);
                        if(window.confirm("是否前往登陆")){
                            window.location.href="#/";
                        }
                    }
                }).catch((error)=> {})
        }
    }


    render(){
        return (
            <div>
                <Title/>
                <div className="editBody">
                    <div className="formGroup">
                        <div className="formTitle">
                            <Breadcrumb icon>
                                <Breadcrumb.Item onClick={()=>{
                                    window.location.href = "#/index"
                                }}>
                                    首页
                                </Breadcrumb.Item>
                                <Breadcrumb.Item active>
                                    会议详情
                                </Breadcrumb.Item>
                            </Breadcrumb>
                        </div>

                        <div className="showBody">
                            <div className="body-left">
                                <div style={{textAlign:"center",marginBottom:"10px"}}><h3>{this.state.data.meetingTitle}</h3></div>
                                <div className="body-content" dangerouslySetInnerHTML={{__html: this.state.data.meetingContent}} />
                            </div>

                            <div className="body-divide">

                            </div>
                            <div className="body-right">
                                <label>会议时间：</label>{this.state.data.meetingTime}<br/>
                                <label>会议地点：</label>{this.state.data.meetingPlace}<br/>
                                <label>主持人：</label>{this.state.data.meetingPresenter}<br/>
                                <label>记录人：</label>{this.state.data.meetingUsername}<br/>
                                <label>参会人员：</label>
                                <div>
                                    <Table>
                                        {this.state.memberList}
                                    </Table>
                                </div>
                                <label>附件：</label>
                                {this.state.attachmentList}
                            </div>

                            {/*弹出层：会议备注*/}
                            <Modal show={this.state.showDecision} onHide={this.close.bind(this)} dialogClassName="ui-note">
                                <Modal.Header closeButton>
                                    <Modal.Title>添加备注</Modal.Title>
                                </Modal.Header>
                                <Modal.Body>
                                    <FormGroup controlId="formControlsTextarea">
                                        <Form.Label required>备注</Form.Label>
                                        <Textarea rows="4" onChange={(e)=>{
                                            this.state.noteContent = e.target.value;
                                            this.setState();
                                        }}/>
                                    </FormGroup>
                                </Modal.Body>
                                <Modal.Footer>
                                    <Button onClick={this.close.bind(this)}>取消</Button>
                                    <Button onClick={this.addNote.bind(this)}>确定</Button>
                                </Modal.Footer>
                            </Modal>
                            <div style={{clear:'both'}}></div>

                            <div className="ui-panel-show">
                                <Panel.Head title="决议情况">
                                    <Button type="button" className="btn-xs" onClick={this.commitProgress.bind(this)}><Icon className="fa-save"/>保存</Button></Panel.Head>
                                <Table striped condensed hover className="ui-decision">
                                    <thead>
                                    <tr>
                                        <th>优先级</th>
                                        <th>决议</th>
                                        <th>截至日期</th>
                                        <th>负责人</th>
                                        <th>总体情况</th>
                                        <th>我的情况</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    {this.state.decitionList}
                                    </tbody>
                                </Table>
                            </div>

                            <div className="ui-panel-show">
                                <Panel.Head title="会议备注"><Button type="button" className="btn-xs" onClick={(e)=>{
                                    this.setState({showDecision:true});
                                }}> <Icon className="fa-plus-square-o"/>备注</Button></Panel.Head>
                                <Table striped condensed hover className="u-note">
                                    <thead>
                                    <tr>
                                        <th>备注人</th>
                                        <th>备注时间</th>
                                        <th style={{width:"60%"}}>备注</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    {this.state.noteList}
                                    </tbody>
                                </Table>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        );
    }
}
export default ShowDetail
